﻿using System;
using System.Windows.Forms;
using System.Xml;
using System.Drawing;
using System.Diagnostics;

namespace VisualExamEngine
{
    public partial class frmMdiChild : Form
    {
        private frmMain MainForm;

        public frmMdiChild(frmMain MainForm)
        {
            InitializeComponent();

            this.MainForm = MainForm;
        }

        /// <summary>
        /// DateTime: 5/4/15 11:58 PM
        /// Author: Mike Hartwig
        /// Purpose: Load event of the mdi child form
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmMdiChild_Load(object sender, EventArgs e)
        {
            webPreview.DocumentCompleted += WebPreview_DocumentCompleted;

            clsExam initialExam = new clsExam("Exam A");

            TreeNode initialNode = new TreeNode();
            initialNode.Text = initialExam.ExamTitle;
            initialNode.Tag = initialExam;

            pgInspector.SelectedObject = initialExam;

            //add an initial sub exam
            this.trvExamExplorer.Nodes.Add(initialNode);

            this.trvExamExplorer.SelectedNode = this.trvExamExplorer.Nodes[0];

            //expand the intial node
            this.trvExamExplorer.Nodes[0].Expand();

            MainForm.tsmMoveDown.Enabled = false;
            MainForm.tsmMoveTo.Enabled = false;
            MainForm.tsmMoveUp.Enabled = false;
        }

        /// <summary>
        /// Document completed of the preview browser control
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void WebPreview_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            HtmlDocument doc = webPreview.Document;
            HtmlElement Calc = doc.GetElementById("calc");
            Calc.Click += Calc_Click;

            HtmlElement Show = doc.GetElementById("show");
            Show.Click += Show_Click;
        }
        /// <summary>
        /// DateTime: 10/27/15 1:58 PM
        /// Author: Mike Hartwig
        /// Purpose: Show the answer div in the preview
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Show_Click(object sender, HtmlElementEventArgs e)
        {
            HtmlDocument doc = webPreview.Document;
            HtmlElement Show = doc.GetElementById("answer");

            if (Show.Style.Contains("DISPLAY") == true)
            {
                Show.Style = "padding:5px;background-color:#FFFFE1;border-style:solid;border-width:1;";
            }
            else
            {
                Show.Style = "padding:5px;background-color:#FFFFE1;border-style:solid;border-width:1;display:none;";
            }
            
        }

        /// <summary>
        /// DateTime: 10/27/15 11:58 PM
        /// Author: Mike Hartwig
        /// Purpose: Show the calculator to the user
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Calc_Click(object sender, HtmlElementEventArgs e)
        {
            Process.Start(@"C:\windows\system32\calc.exe");
        }

        /// <summary>
        /// DateTime: 5/6/15 11:58 PM
        /// Author: Mike Hartwig
        /// Purpose: Enable disable some gui items on the main form
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmMdiChild_FormClosing(object sender, FormClosingEventArgs e)
        {
            //menu items
            MainForm.tsmClose.Enabled = false;
            MainForm.tsmSave.Enabled = false;
            MainForm.tsmSaveAs.Enabled = false;
            MainForm.tsmPageSetup.Enabled = false;
            MainForm.tsmPrint.Enabled = false;
            MainForm.tsmPrintPreview.Enabled = false;
            MainForm.tsmUndo.Enabled = false;
            MainForm.tsmRedo.Enabled = false;
            MainForm.tsmMoveTo.Enabled = false;
            MainForm.tsmMoveDown.Enabled = false;
            MainForm.tsmMoveUp.Enabled = false;
            MainForm.tsmPreviousItem.Enabled = false;
            MainForm.tsmNextItem.Enabled = false;
            MainForm.tsmGoTo.Enabled = false;
            MainForm.tsmExamProperties.Enabled = false;
            MainForm.tsmNewQuestion.Enabled = false;
            MainForm.tsmNewExam.Enabled = false;
            MainForm.tsmSelect.Enabled = false;
            MainForm.tsmCut.Enabled = false;
            MainForm.tsmCopy.Enabled = false;
            MainForm.tsmPaste.Enabled = false;
            MainForm.tsmDelete.Enabled = false;
            MainForm.tsmFind.Enabled = false;
            MainForm.tsmFindNext.Enabled = false;
            MainForm.tsmReplace.Enabled = false;

            //tool buttons
            MainForm.tsbPrintPreview.Enabled = false;
            MainForm.tsbReplace.Enabled = false;
            MainForm.tsbRedo.Enabled = false;
            MainForm.tsbUndo.Enabled = false;
            MainForm.tsbSave.Enabled = false;
            MainForm.tsbPrint.Enabled = false;
            MainForm.tsbGoTo.Enabled = false;
            MainForm.tsbNext.Enabled = false;
            MainForm.tsbPrevious.Enabled = false;
            MainForm.tsbPicture.Enabled = false;
            MainForm.tsbCut.Enabled = false;
            MainForm.tsbFind.Enabled = false;
            MainForm.tsbCopy.Enabled = false;
            MainForm.tsbPaste.Enabled = false;
        }

        /// <summary>
        /// DateTime: 5/16/15 11:58 PM
        /// Author: Mike Hartwig
        /// Purpose: Load an XML based question template
        /// </summary>
        /// <param name="filepath"></param>
        private void LoadQuestionTemplate(string filepath, Panel pnlQuestion)
        {
            XmlTextReader xmlReader = new XmlTextReader(filepath);

            while (xmlReader.Read())
            {
                if (xmlReader.NodeType == XmlNodeType.Element)
                {
                    if (xmlReader.GetAttribute("Type") != null)
                    {
                        if (xmlReader.GetAttribute("Type") == "Label")
                        {
                            Label lbl = new Label();

                            if (xmlReader.GetAttribute("Width").Contains("%"))
                            {
                                lbl.Width = pnlQuestion.Width;
                            }
                            else
                            {
                                lbl.Width = Convert.ToInt32(xmlReader.GetAttribute("Width"));
                            }

                            lbl.Left = Convert.ToInt32(xmlReader.GetAttribute("Left").Replace("px", ""));

                            lbl.Top = Convert.ToInt32(xmlReader.GetAttribute("Top").Replace("px", ""));

                            lbl.Text = xmlReader.ReadElementString();

                            lbl.BackColor = Color.DarkGray;
                            lbl.ForeColor = Color.White;
                            lbl.TextAlign = ContentAlignment.MiddleLeft;

                            pnlQuestion.Controls.Add(lbl);
                        }
                        else if (xmlReader.GetAttribute("Type") == "Radio")
                        {
                            RadioButton rdo = new RadioButton();

                            if (xmlReader.GetAttribute("Width").Contains("%"))
                            {
                                int perc = Convert.ToInt32(xmlReader.GetAttribute("Width").ToString().Replace("%", string.Empty));
                                int num = (pnlQuestion.Width * perc) / 100;
                                rdo.Width = num;
                            }
                            else
                            {
                                rdo.Width = Convert.ToInt32(xmlReader.GetAttribute("Width").Replace("px", string.Empty));
                            }

                            if (xmlReader.GetAttribute("Left").Contains("%"))
                            {
                                int perc = Convert.ToInt32(xmlReader.GetAttribute("Left").ToString().Replace("%", string.Empty));
                                int num = (pnlQuestion.Width * perc) / 100;
                                rdo.Left = num;
                            }
                            else
                            {
                                rdo.Left = Convert.ToInt32(xmlReader.GetAttribute("Left").Replace("px", ""));
                            }

                            rdo.Top = Convert.ToInt32(xmlReader.GetAttribute("Top").Replace("px", ""));

                            rdo.Height = 20;

                            pnlQuestion.Controls.Add(rdo);
                        }
                        else if (xmlReader.GetAttribute("Type") == "RichTextBox")
                        {
                            RichTextBox rtb = new RichTextBox();

                            rtb.BorderStyle = BorderStyle.FixedSingle;

                            if (xmlReader.GetAttribute("Width").Contains("%"))
                            {
                                int perc = Convert.ToInt32(xmlReader.GetAttribute("Width").ToString().Replace("%", string.Empty));
                                int num = (pnlQuestion.Width * perc) / 100;
                                rtb.Width = num;
                            }
                            else
                            {
                                rtb.Width = Convert.ToInt32(xmlReader.GetAttribute("Width"));
                            }

                            if (xmlReader.GetAttribute("Left").Contains("%"))
                            {
                                int perc = Convert.ToInt32(xmlReader.GetAttribute("Left").ToString().Replace("%", string.Empty));
                                int num = (pnlQuestion.Width * perc) / 100;
                                rtb.Left = num;
                            }
                            else
                            {
                                rtb.Left = Convert.ToInt32(xmlReader.GetAttribute("Left").Replace("px", ""));
                            }

                            rtb.Top = Convert.ToInt32(xmlReader.GetAttribute("Top").Replace("px", ""));

                            rtb.KeyDown += Rtb_KeyDown;

                            rtb.Height = 20;

                            pnlQuestion.Controls.Add(rtb);
                        }
                    }
                }
            }
        }

        /// <summary>
        /// DateTime: 10/28/15 11:58 PM
        /// Author: Mike Hartwig
        /// Purpose: Keydown for richtextbox
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Rtb_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                e.SuppressKeyPress = true;
            }
        }



        /// <summary>
        /// DateTime: 5/7/15 11:58 PM
        /// Author: Mike Hartwig
        /// Purpose: User clicked a node in the exam explorer window
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void trvExamExplorer_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node.Level == 0)
            {
                MainForm.tsmNewQuestion.Enabled = true;

                this.pnlQuestionListing.Visible = true;
                this.pnlQuestionDetail.Visible = false;

                this.pnlQuestionListing.Dock = DockStyle.Fill;

                this.lstQuestionListing.Items.Clear();

                //disable some gui items
                MainForm.tsmMoveDown.Enabled = false;
                MainForm.tsmMoveTo.Enabled = false;
                MainForm.tsmMoveUp.Enabled = false;

                pgInspector.SelectedObject = (clsExam) this.trvExamExplorer.SelectedNode.Tag;

                //show all questions in the listview
                foreach (TreeNode node in e.Node.Nodes)
                {
                    clsQuestion q = (clsQuestion)node.Tag;

                    ListViewItem qItem = new ListViewItem();

                    qItem.Text = "Question " + q.Number;

                    qItem.SubItems.Add(q.Type);

                    if (q.Section.Count > 0)
                    {
                        qItem.SubItems.Add(q.Section[q.SelectedSection]);
                    }
                    else
                    {
                        qItem.SubItems.Add("(none)");
                    }


                    this.lstQuestionListing.Items.Add(qItem);
                }
            }
            else
            {
                MainForm.tsmNewQuestion.Enabled = false;

                this.pnlQuestionListing.Visible = false;
                this.pnlQuestionDetail.Visible = true;

                this.pnlQuestionDetail.Dock = DockStyle.Fill;

                //enable some gui items
                MainForm.tsmMoveDown.Enabled = true;

                pgInspector.SelectedObject = (clsQuestion)this.trvExamExplorer.SelectedNode.Tag;

                //clear the controls to prepare for the loading of the new template
                pnlDetails.Controls.Clear();

                //load the question template
                LoadQuestionTemplate(Application.StartupPath + @"\Templates\multiplechoice_single_select.xml", pnlDetails);

                this.tabQuestion.SelectedIndex = 0;

                if (this.trvExamExplorer.Nodes.Count > 1)
                {
                    MainForm.tsmMoveTo.Enabled = true;
                }
                else
                {
                    MainForm.tsmMoveTo.Enabled = false;
                }

                MainForm.tsmMoveUp.Enabled = true;

                if (e.Node.Text.Contains("1"))
                {
                    if (e.Node.Parent.Nodes.Count == 1)
                    {
                        MainForm.tsmMoveUp.Enabled = false;
                        MainForm.tsmMoveDown.Enabled = false;
                    }
                    else
                    {
                        MainForm.tsmMoveUp.Enabled = false;
                        MainForm.tsmMoveDown.Enabled = true;
                    }
                }
                else if (e.Node.Text.Contains(e.Node.Parent.Nodes.Count.ToString()))
                {
                    MainForm.tsmMoveUp.Enabled = true;
                    MainForm.tsmMoveDown.Enabled = false;
                }
                else
                {
                    MainForm.tsmMoveUp.Enabled = true;
                    MainForm.tsmMoveDown.Enabled = true;
                }
            }
        }

        /// <summary>
        /// DateTime: 5/18/15 11:58 PM
        /// Author: Mike Hartwig
        /// Purpose: User resized the child form
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmMdiChild_Resize(object sender, EventArgs e)
        {
            if (this.trvExamExplorer.SelectedNode != null)
            {
                if (this.trvExamExplorer.SelectedNode.Level == 1)
                {
                    //resize all the controls
                    foreach (Control ctrl in pnlDetails.Controls)
                    {
                        ctrl.Width = pnlDetails.Width;
                    }
                }
            }
        }

        /// <summary>
        /// DateTime: 5/25/15 11:58 PM
        /// Author: Mike Hartwig
        /// Purpose: User changed the tab index for the selected question
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tabQuestion_SelectedIndexChanged(object sender, EventArgs e)
        {
            clsQuestion selQeus = (clsQuestion)this.trvExamExplorer.SelectedNode.Tag;

            string QuestionText = ((RichTextBox)pnlDetails.Controls[1]).Text;

            string remainder = string.Format("<div style=\"background-color:A9A9A9;\">Question</div>" + QuestionText +
                "<br><br><div style=\"background-color:A9A9A9;\">Choices {0}</div>", selQeus.Type.Substring(selQeus.Type.IndexOf("(")));

            string questionHTML = "";

            switch (selQeus.Type)
            {
                case "Multiple Choice (Single Select)":
                    questionHTML = "";

                    for (int i = 3; i <= pnlDetails.Controls.Count - 3; i++)
                    {
                        if (pnlDetails.Controls[i] is RichTextBox)
                        {
                            string Possibility = ((RichTextBox)pnlDetails.Controls[i]).Text;
                            questionHTML += string.Format("<input type=\"radio\" id=\"{0}\" value=\"{1}\">{1}<br>", i.ToString(), Possibility);
                        }
                    }

                    remainder += questionHTML;

                    remainder += string.Format("<br><div id=\"answer\" style=\"padding:5px;background-color:#FFFFE1;border-style:solid;border-width:1px;display:none;\">Answer: <br><br>{0}</div>", ((RichTextBox)pnlDetails.Controls[pnlDetails.Controls.Count - 1]).Text);

                    break;
                case "Multiple Choice (Multi Select)":
                    questionHTML = "";

                    for (int i = 3; i <= pnlDetails.Controls.Count - 3; i++)
                    {
                        string Possibility = ((RichTextBox)pnlDetails.Controls[i]).Text;
                        questionHTML += string.Format("<input type=\"radio\" id=\"{0}\" value=\"{1}\">{1}<br>", i.ToString(), Possibility);
                    }

                    remainder += questionHTML;

                    break;
            }

            int innerIndex = this.trvExamExplorer.SelectedNode.Index - this.trvExamExplorer.SelectedNode.Parent.Index;

            string itemCount = String.Format("Item {0} of {1}", (innerIndex + 1).ToString(), this.trvExamExplorer.SelectedNode.Parent.Nodes.Count.ToString());

            //generate the html page preview
            webPreview.DocumentText = String.Format(@"<table style='width: 100 %;'><tbody> <tr> <td> {0} </td><td style='text-align:right'> <button type='button' id='show'>Show Answer</button><button id='calc' type='button'>Calculator</button> </td></tr></tbody></table><hr>", itemCount)
                + remainder;
        }

        /// <summary>
        /// User updated the property grid
        /// </summary>
        /// <param name="s"></param>
        /// <param name="e"></param>
        private void pgInspector_PropertyValueChanged(object s, PropertyValueChangedEventArgs e)
        {
            if (e.ChangedItem.PropertyDescriptor.DisplayName == "ExamTitle")
            {
                this.trvExamExplorer.SelectedNode.Text = (string)e.ChangedItem.Value;

                clsExam selExam = (clsExam) this.trvExamExplorer.SelectedNode.Tag;

                selExam.ExamTitle = (string)e.ChangedItem.Value;
            }
        }
    }
}
